import { ref, computed, onMounted } from 'vue'
import { defineStore } from 'pinia'

import {
  getLocalCity,
  getCityAdcode,
  getWeatherByAdcodeLive,
  getWeatherByAdcodeForecast,
} from '@/api/index.js'

export const useWeatherStore = defineStore('weather', () => {
  const localCity = ref({})
  const localCityName = ref('')
  const localCityAdcode = ref('')
  const localCityWeather = ref('')
  const localCityTemperature = ref('')
  const localCityWindDirection = ref('')
  const localCityWindPower = ref('')
  const localCityForecast = ref('')
  const localCityForecasts = ref('')

  const day1 = ref('')
  const day2 = ref('')
  const day3 = ref('')
  const day4 = ref('')

  const searchCityInfo = ref('')
  const cityAdcode = ref('')
  const cityWeatherLive = ref('')
  const cityWeatherForecast = ref('')
  
  onMounted(async () => {
    localCity.value = await getLocalCity()
    localCityName.value = localCity.value.city
    // console.log(localCity.value)
    localCityAdcode.value = localCity.value.adcode
    // console.log(localCityAdcode.value)

    cityAdcode.value = await getCityAdcode()
    //获取当地天气相关信息
    cityWeatherLive.value = await getWeatherByAdcodeLive(localCity.value)
    localCityWeather.value = cityWeatherLive.value.lives[0].weather
    localCityTemperature.value = cityWeatherLive.value.lives[0].temperature
    localCityWindDirection.value = cityWeatherLive.value.lives[0].winddirection
    localCityWindPower.value = cityWeatherLive.value.lives[0].windpower
    // console.log(cityWeatherLive.value)

    //获取未来天气相关信息
    localCityForecast.value = await getWeatherByAdcodeForecast(localCity.value)
    localCityForecasts.value = localCityForecast.value.forecasts[0].casts
    day1.value = localCityForecasts.value[0]
    day2.value = localCityForecasts.value[1]
    day3.value = localCityForecasts.value[2]
    day4.value = localCityForecasts.value[3]
    // console.log(day1.value, day2.value, day3.value, day4.value)
    // console.log(localCityForecasts.value)
  })

  return {
    localCity,
    localCityName,
    cityAdcode,
    localCityWeather,
    localCityTemperature,
    localCityWindDirection,
    localCityWindPower,
    localCityForecast,
    localCityForecasts,
    day1,
    day2,
    day3,
    day4,

    searchCityInfo,
    cityWeatherLive,
    cityWeatherForecast,
    getCityAdcode,
  }
})
